const express = require('express');
const appConfig = require('../conf');
const session = require('express-session');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { log } = require('console');
const CM = require('connect-multiparty')();
const cors = require("cors");


module.exports = {
    init: function (app) {
        //设置模板引擎
        app.set('views', path.join(__dirname, '../views'));
        app.set('view engine', 'ejs');
        app.use(cors());

        //设置静态资源
        app.use(express.static(path.join(__dirname, '..', 'public')));

        //解析post数据需要加载以下两个中间件
        app.use(express.urlencoded({ extended: true }));
        app.use(express.json());

        app.all('*', function (req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
            res.header("X-Powered-By", ' 3.2.1')
            res.header("Content-Type", "application/json;charset=utf-8");
            if (req.method == 'OPTIONS') {
                /*让options请求快速返回*/
                res.sendStatus(200)
            } else {
                next()
            }

        });
        app.use(cookieParser());
        app.use(logger('dev'));
        app.use(session(appConfig.session))
        app.use(CM);
    },

    //项目启动
    run: function (app) {
        this.init(app);
        app.use(this.router);
        require('../routes')(app);
    },

    //路由引导
    router: function (req, res, next) {
        // console.log('11111->',req.hostname);
        // console.log(appConfig['modules']);
        //console.log('路由导航',appConfig['modules'][req.hostname]);
        req.moduleName = appConfig['modules'][req.hostname];  //对应的模块名
        next();
    }
}